// pages/pending-payment/pending-payment.js
Page({
  data: {
    patientInfo: {
      name: '',
      relation: '本人',
      idNumber: ''
    },
    cardBalance: '4100.00',
    showPatientModal: false,
    patientList: [],
    paymentItems: [
      {
        id: 1,
        name: '西药费',
        department: '神经内科',
        doctor: '刘美',
        dateTime: '2020-06-15 11:05',
        amount: '300.00'
      },
      {
        id: 2,
        name: '检验费',
        department: '神经内科',
        doctor: '王医生',
        dateTime: '2020-06-15 11:05',
        amount: '200.00'
      },
      {
        id: 3,
        name: '检查费',
        department: '神经内科',
        doctor: '张医生',
        dateTime: '2020-06-15 11:05',
        amount: '150.00'
      }
    ]
  },

  onLoad(options) {
    console.log('待缴费项目页面加载');
    this.loadPatientInfo();
  },

  // 加载就诊人信息
  loadPatientInfo() {
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
          }))
          
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
                }
              })
            }
          }
        }
      }
    })
  },

  // 切换就诊人
  switchPatient() {
    this.setData({
      showPatientModal: true
    });
  },

  // 关闭模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 选择就诊人
  selectPatient(e) {
    const patient = e.currentTarget.dataset.patient;
    console.log('选择了就诊人:', patient);
    
    this.setData({
      patientInfo: patient,
      showPatientModal: false
    });

    // 保存到本地存储
    const cacheUser = wx.getStorageSync('userInfo') || {}
    wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
  },

  // 去缴费
  goToPayment(e) {
    const item = e.currentTarget.dataset.item;
    console.log('去缴费:', item);
    
    // 跳转到确认缴费信息页面
    wx.navigateTo({
      url: `/pages/confirm-payment/confirm-payment?amount=${item.amount}&itemName=${item.name}`
    });
  }
});
